package cn.edu.whu.forecast.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;


@Component
public class CORSInterceptor extends HandlerInterceptorAdapter {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        String []  allowDomain= {"http://localhost:8080","http://10.35.80.145:8080"};
        Set allowedOrigins= new HashSet(Arrays.asList(allowDomain));
        String originHeader= request.getHeader("Origin");
        if(allowedOrigins.contains(originHeader)){
            response.setHeader("Access-Control-Allow-Origin", originHeader);
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS");
            response.setHeader("Access-Control-Max-Age", "8640000");
            response.setHeader("Access-Control-Allow-Headers", "*");
            response.setHeader("Content-Type", "application/json;charset=utf-8");
        }
        //预检请求返回
        if (request.getMethod().equals("OPTIONS")){
            response.setStatus(200);
            return false;
        }
        return true;
    }

}

